extends Node

# 后端API地址
var API_URL = "http://14.103.140.183/api"
var API_URL2:String:
	get:
		if OS.has_feature("windows"):
			return "http://127.0.0.1:5000/api"
		else:
			return "http://14.103.140.183/api"


# 用户数据
var user_data = null
var access_token = null
var refresh_token = null

func _ready():

	# 加载令牌和用户数据
	load_tokens()
	load_user_data()

# 检查会话是否有效
func check_session() -> bool:
	# 如果没有令牌，会话无效
	if not access_token or access_token.is_empty():
		return false

	# 调用/api/auth/me接口验证令牌
	var result: HTTPResult = await request_with_auth("/auth/me")

	if not result.success() or result.status_err():
		# 尝试使用刷新令牌
		if refresh_token != null and not refresh_token.is_empty():
			var refreshed = await refresh_token_request()
			return refreshed
		return false

	# 更新用户数据
	var json_response = result.body_as_json()
	if json_response is Dictionary and json_response.has("user"):
		user_data = json_response["user"]
		save_user_data()
		return true

	return false

# 刷新令牌
func refresh_token_request() -> bool:
	var headers = PackedStringArray([
		"Content-Type: application/json",
		"Accept: application/json",
		"Authorization: Bearer " + refresh_token
	])

	var result: HTTPResult = await AwaitableHTTPRequest.async_request(
		API_URL + "/auth/refresh",
		headers,
		HTTPClient.METHOD_POST,
		""
	)

	if not result.success() or result.status_err():
		# 刷新失败，清除所有令牌
		clear_tokens()
		return false

	# 解析新的访问令牌
	var json_response = result.body_as_json()
	if json_response is Dictionary and json_response.has("access_token"):
		access_token = json_response["access_token"]
		save_tokens()
		return true

	return false

# 带认证的请求
func request_with_auth(endpoint: String, method: int = HTTPClient.METHOD_GET, data: String = "") -> HTTPResult:
	var headers = PackedStringArray([
		"Content-Type: application/json",
		"Accept: application/json",
		"Authorization: Bearer " + access_token
	])

	return await AwaitableHTTPRequest.async_request(
		API_URL + endpoint,
		headers,
		method,
		data
	)

# 检查后端健康状态
func check_backend_health() -> Dictionary:
	var result: HTTPResult = await AwaitableHTTPRequest.async_request(API_URL + "/health")

	if not result.success() or result.status_err():
		print("无法连接到后端服务")
		return {"status": "error", "message": "无法连接到后端服务"}

	var response = result.body_as_json()
	if response is Dictionary and response.has("status") and response["status"] == "ok":
		print("后端服务状态: 正常")
		return response
	else:
		print("后端服务状态: ", result.body_as_string())
		return {"status": "unknown", "message": result.body_as_string()}

# 从本地加载用户数据
func load_user_data():
	# 尝试从本地加载用户数据
	var config = ConfigFile.new()
	var err = config.load("user://user_data.cfg")
	if err != OK:
		print("加载用户数据失败或文件不存在: ", err)
		return

	# 获取用户数据
	user_data = config.get_value("user", "data", null)

# 保存用户数据到本地
func save_user_data():
	if not user_data:
		return

	var config = ConfigFile.new()
	config.set_value("user", "data", user_data)
	var err = config.save("user://user_data.cfg")
	if err != OK:
		print("保存用户数据失败: ", err)

# 清除用户数据
func clear_user_data():
	user_data = null
	var dir = DirAccess.open("user://")
	if dir and dir.file_exists("user_data.cfg"):
		dir.remove("user_data.cfg")

# 从本地加载令牌
func load_tokens() -> void:
	var config = ConfigFile.new()
	var err = config.load("user://auth.cfg")
	if err != OK:
		return

	access_token = config.get_value("auth", "access_token", "")
	refresh_token = config.get_value("auth", "refresh_token", "")

	if not access_token.is_empty() and not refresh_token.is_empty():
		print("已从本地加载令牌")

# 保存令牌到本地
func save_tokens() -> void:
	if access_token and refresh_token:
		var config = ConfigFile.new()
		config.set_value("auth", "access_token", access_token)
		config.set_value("auth", "refresh_token", refresh_token)
		var err = config.save("user://auth.cfg")
		if err != OK:
			push_error("保存令牌失败: %s" % err)

# 清除令牌
func clear_tokens() -> void:
	access_token = ""
	refresh_token = ""

	var dir = DirAccess.open("user://")
	if dir and dir.file_exists("auth.cfg"):
		dir.remove("auth.cfg")

# 清除所有数据（用户数据和令牌）
func clear_all_data() -> void:
	clear_user_data()
	clear_tokens()

# 登录请求
func login(username: String, password: String) -> Dictionary:
	var data = JSON.stringify({
		"username": username,
		"password": password
	})

	var headers = PackedStringArray([
		"Content-Type: application/json",
		"Accept: application/json"
	])

	var result: HTTPResult = await AwaitableHTTPRequest.async_request(
		API_URL + "/auth/login",
		headers,
		HTTPClient.METHOD_POST,
		data
	)

	if not result.success() or result.status_err():
		var error_message = "登录失败"
		if result.status == 401:
			error_message = "用户名或密码错误"
		elif result.status == 400:
			var response = result.body_as_json()
			if response is Dictionary and response.has("message"):
				error_message = response["message"]

		return {"success": false, "message": error_message}

	var response = result.body_as_json()
	if response is Dictionary and response.has("access_token") and response.has("refresh_token"):
		access_token = response["access_token"]
		refresh_token = response["refresh_token"]

		if response.has("user"):
			user_data = response["user"]
			save_user_data()

		save_tokens()
		return {"success": true, "user": user_data}

	return {"success": false, "message": "登录响应格式错误"}

# 注册请求
func register(username: String, email: String, password: String) -> Dictionary:
	var data = JSON.stringify({
		"username": username,
		"email": email,
		"password": password
	})

	var headers = PackedStringArray([
		"Content-Type: application/json",
		"Accept: application/json"
	])

	var result: HTTPResult = await AwaitableHTTPRequest.async_request(
		API_URL + "/auth/register",
		headers,
		HTTPClient.METHOD_POST,
		data
	)

	if not result.success() or result.status_err():
		var error_message = "注册失败"
		if result.status == 400:
			var response = result.body_as_json()
			if response is Dictionary and response.has("message"):
				error_message = response["message"]

		return {"success": false, "message": error_message}

	var response = result.body_as_json()
	if response is Dictionary and response.has("message"):
		return {"success": true, "message": response["message"]}

	return {"success": false, "message": "注册响应格式错误"}
